/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.citi.dahg.cve.converter;

import com.citi.dahg.cve.commons.ServiceBean;
import com.citi.dahg.cve.controller.model.CatalogEntity;
import com.citi.dahg.cve.controller.service.Service;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author dh90940
 */
public abstract class AbstractConverter<T extends CatalogEntity> implements Converter {
    
    protected abstract String getServiceName();

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        Object id = convertStringToPrimaryKey(value);
        return getService().findById(id);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        T obj = (T) value;
        return obj.getPrimaryKey().toString();
    }
    
    private Service<T> getService() {
        String elExpression=String.format("#%s%s%s","{",getServiceName(),"}");               
        FacesContext ctx= FacesContext.getCurrentInstance();
        ServiceBean<T> bean = (ServiceBean<T>) ctx.getApplication().evaluateExpressionGet(ctx, elExpression, Object.class);
        return bean.getService();
    }
    
    protected abstract Object convertStringToPrimaryKey(String value);
}
